import threading
import time

# 获取锁对象
lock = threading.Lock()


class Account:
    def __init__(self, balance):
        self.balance = balance


def draw(account, amount):
    # 使用with关键字对发生线程安全的代码进行加锁, 当一个线程执行完成之后才会释放锁另外一个线程才可以获取到锁
    with lock:
        if account.balance >= amount:
            # 调用sleep()大概率会出现问题
            time.sleep(0.1)
            print(threading.current_thread().name + "取钱成功")
            account.balance -= amount
            print(threading.current_thread().name + " 余额: ", account.balance)

        else:
            print(threading.current_thread().name, "取钱失败, 余额不足")


if __name__ == '__main__':
    account = Account(1000)
    ta = threading.Thread(name="a", target=draw, args=(account, 800))
    tb = threading.Thread(name="b", target=draw, args=(account, 800))
    ta.start()
    tb.start()